package com.liuxin.mycontactdemo.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.liuxin.mycontactdemo.R;
import com.liuxin.mycontactdemo.provider.ContactProvider;
import com.liuxin.mycontactdemo.untils.ThreadUtils;
import com.liuxin.mycontactdemo.untils.ToastUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class MainActivity extends AppCompatActivity {
    @InjectView(R.id.mainLv)
    ListView mainLv;
    private CursorAdapter cursorAdapter;
    private  Cursor currentCursor;
    private MyContentObserver contentObserver=new MyContentObserver(new Handler());//内容观察者对象
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private final String PREFS_NAME = "data";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        preferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        editor = preferences.edit();
        initData();
        initListener();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getContentResolver().unregisterContentObserver(contentObserver);
    }

    private void initListener() {
        getContentResolver().registerContentObserver(ContactProvider.URI_CONTACT,true,contentObserver);
        registerForContextMenu(mainLv);
        mainLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                currentCursor= (Cursor) parent.getItemAtPosition(position);
                return false;//false表示该事件向外传播，这样可以激发上下文菜单
            }
        });
    }

    private void initData() {
        setOrUpdateAdapter();
    }

    private void setOrUpdateAdapter() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                if (cursorAdapter != null) {
                    cursorAdapter.getCursor().requery();
                    return;
                }
                Cursor cursor = getContentResolver().query(ContactProvider.URI_CONTACT, null, null, null, null);
                if (cursor.getCount() == 0)
                    return;
                cursorAdapter = new CursorAdapter(MainActivity.this, cursor) {
                    @Override
                    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
                        View view = View.inflate(context, R.layout.datalist, null);
                        return view;
                    }

                    @Override
                    public void bindView(View view, Context context, Cursor cursor) {
                        TextView nameTv = view.findViewById(R.id.nameTv_datalist);
                        TextView phoneTv = view.findViewById(R.id.phoneTv_datalist);
                        TextView emailTv = view.findViewById(R.id.emailTv_datalist);
                        TextView qqTv = view.findViewById(R.id.qqTv_datalist);
                        nameTv.setText(cursor.getString(1));
                        phoneTv.setText(cursor.getString(2));
                        emailTv.setText(cursor.getString(3));
                        qqTv.setText(cursor.getString(4));
                    }
                };
                mainLv.setAdapter(cursorAdapter);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1, Menu.FIRST, 1, "新建联系人").setIcon(R.drawable.new_contact);
        menu.add(1, Menu.FIRST + 1, 2, "查找联系人").setIcon(R.drawable.search_contact);
        menu.add(1, Menu.FIRST + 2, 3, "导入联系人").setIcon(R.drawable.import_contact);
        menu.add(1, Menu.FIRST + 3, 4, "导出联系人").setIcon(R.drawable.export_contact);
        menu.add(1, Menu.FIRST + 4, 5, "修改密码").setIcon(R.drawable.modify_password);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            case Menu.FIRST:
                addContact();
                break;
            case Menu.FIRST + 1:
                findContact();
                break;
            case Menu.FIRST + 2:
                importContact();
                break;
            case Menu.FIRST + 3:
                exportContact();
                break;
            case Menu.FIRST + 4:
                modiPassWord();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("联系人操作");
        menu.add(Menu.NONE,Menu.FIRST,1,"编辑联系人");
        menu.add(Menu.NONE,Menu.FIRST+1,2,"删除联系人");
        menu.add(Menu.NONE,Menu.FIRST+2,3,"拨打电话");
        menu.add(Menu.NONE,Menu.FIRST+3,4,"发送短信");
        menu.add(Menu.NONE,Menu.FIRST+4,5,"发送邮件");
        menu.add(Menu.NONE,Menu.FIRST+5,6,"显示全部联系人");
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case Menu.FIRST:
                editContact();
                break;
            case Menu.FIRST + 1:
                delContact();
                break;
            case Menu.FIRST + 2:
                dial();
                break;
            case Menu.FIRST + 3:
                message();
                break;
            case Menu.FIRST + 4:
                email();
                break;
            case Menu.FIRST + 5:
                mainLv.setAdapter(cursorAdapter);//显示全部联系人
                setOrUpdateAdapter();
                break;

        }
        return super.onContextItemSelected(item);
    }



    private void editContact() {
        Intent intent=new Intent(this,EditContactActivity.class);
        intent.putExtra("name",currentCursor.getString(1));
        intent.putExtra("phone",currentCursor.getString(2));
        intent.putExtra("email",currentCursor.getString(3));
        intent.putExtra("qq",currentCursor.getString(4));
        startActivity(intent);
    }

    private void delContact() {
        getContentResolver().delete(ContactProvider.URI_CONTACT,"name=?",new String[]{currentCursor.getString(1)});
        ToastUtils.showToastSafe(this,currentCursor.getString(1)+"联系人删除成功！！！");
    }

    private void dial() {
        //拨打电话
        Intent intent=new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:"+currentCursor.getString(2)));
        startActivity(intent);
    }

    private void message() {
        //发送短信
        Uri uri = Uri.parse("smsto:"+currentCursor.getString(2));
        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
        intent.putExtra("sms_body", "你好啊，"+currentCursor.getString(1));
        startActivity(intent);
    }

    private void email() {
        Intent it = new Intent(Intent.ACTION_SEND);
        it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
        it.putExtra(Intent.EXTRA_TEXT, "The email body text");
        it.setType("text/plain");
        startActivity(Intent.createChooser(it, "Choose Email Client"));
//        Uri uri = Uri.parse("mailto:825848883@qq.com");
//        String[] email = { "825848883@qq.com" };
//        Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
//        intent.putExtra(Intent.EXTRA_CC, email); // 抄送人
//        intent.putExtra(Intent.EXTRA_SUBJECT, "这是邮件的主题部分"); // 主题
//        intent.putExtra(Intent.EXTRA_TEXT, "这是邮件的正文部分"); // 正文
//        startActivity(Intent.createChooser(intent, "请选择邮件类应用"));
    }

    private void addContact() {
        Intent intent=new Intent(this,AddContactActivity.class);
        startActivity(intent);
    }

    private void findContact() {
        final EditText editText=new EditText(this);
        AlertDialog.Builder searchDialog=new AlertDialog.Builder(this);
        searchDialog.setTitle("请输入要查找的姓名")
                .setView(editText)
                .setPositiveButton("查找", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        searchByName(editText.getText().toString());
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                })
                .show();
    }

    private void searchByName(final String name) {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                Cursor cursor=getContentResolver().query(ContactProvider.URI_CONTACT,
                        null,
                        "name like ?",
                        new String[]{"%"+name+"%"},
                        null);
                if(cursor.getCount()==0)
                {
                    ToastUtils.showToastSafe(MainActivity.this,"没有找到该联系人！！！");
                    return;
                }
                CursorAdapter searchResultAdapter=new CursorAdapter(MainActivity.this,cursor) {
                    @Override
                    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
                        View view=View.inflate(context,R.layout.datalist,null);
                        return view;
                    }

                    @Override
                    public void bindView(View view, Context context, Cursor cursor) {
                        TextView nameTv=view.findViewById(R.id.nameTv_datalist);
                        TextView phoneTv=view.findViewById(R.id.phoneTv_datalist);
                        TextView emailTv=view.findViewById(R.id.emailTv_datalist);
                        TextView qqTv=view.findViewById(R.id.qqTv_datalist);
                        nameTv.setText(cursor.getString(1));
                        phoneTv.setText(cursor.getString(2));
                        emailTv.setText(cursor.getString(3));
                        qqTv.setText(cursor.getString(4));


                    }
                };
                mainLv.setAdapter(searchResultAdapter);
            }
        });
    }

    private void importContact() {
        Intent intent=new Intent(this,ImportContactActivity.class);
        startActivity(intent);
    }

    private void exportContact() {
        // 将所有数据传到 exportContactActivity 中，或者在 exportContactActivity 中加载所有数据
        Intent intent = new Intent(this, ExportContactActivity.class);
        startActivity(intent);
    }

    private void modiPassWord() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("修改密码");
        View view = getLayoutInflater().inflate(R.layout.activity_modifypwd, null);
        final EditText newpwdET = (EditText) view.findViewById(R.id.newpwdET);
        final EditText renewpwdET = (EditText) view.findViewById(R.id.renewpwdET);
        builder.setView(view);
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 先获取存储的密码
                String pwdString = preferences.getString("password", "123456");
                String first_password = newpwdET.getText().toString().trim();
                String end_password = renewpwdET.getText().toString().trim();
                if (end_password.equals(pwdString)) {
                    Toast.makeText(MainActivity.this, "输入的新密码与原始密码不能一致", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(first_password)) {
                    Toast.makeText(MainActivity.this, "请输入初始密码", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(end_password)) {
                    Toast.makeText(MainActivity.this, "请输入修改密码", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "密码修改成功！", Toast.LENGTH_SHORT).show();
                    modifyPsw(end_password);
                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            }
            private void modifyPsw(String newPsw) {
                editor.putString("password", newPsw);
                editor.apply();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this, "取消登录", Toast.LENGTH_SHORT).show();
            }
        });
        builder.show();

    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        //反身机制 通过类找到对象
        if (menu != null) {
            if (menu.getClass().getSimpleName().equalsIgnoreCase("MenuBuilder")) {
                try {
                    Method method = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    method.setAccessible(true);
                    method.invoke(menu, true);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }
    class MyContentObserver extends ContentObserver
    {

        public MyContentObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            setOrUpdateAdapter();
        }
    }
}
